import { mapGetters } from 'vuex'
import { excelJsonExport, columnToAbc } from '@vimi/utils-tool'
import { exportTableColumns, exportTableCountyColumns } from '@/bank/views/limit/index'
import { getAddressNextValue } from '@/common/api/address'
import { queryTrouble, service as axios } from '@vimi/utils-api'
// 限率正常列表
export const limitNormalParams = {
  computed: {
    ...mapGetters(['user', 'userId', 'clientId']),
    isSubmit() {
      return this.user.scopes.includes('indoneBI')
    },
    noNextBank() {
      // 安顺市平坝区农村信用合作联社
      return ['10'].includes(this.bankType) && !this.isSubmit
    },
    normalParams() {
      const { queryAddressCode, clientOrgClassType } = this.user
      if (!queryAddressCode) {
        this.$message.error('机构配置出错，未添加机构地址')
        throw new Error('该机构没有地址')
      }
      return {
        orWhereAndTemplate: 2,
        'orWhereAnd.bank_id.eq': this.clientId,
        'orWhereAnd.bank_type.in': clientOrgClassType,
        'orWhereAnd.address_code.gt': queryAddressCode,
        'orWhereAnd.address_code.lt': getAddressNextValue(queryAddressCode),
        'orWhereAnd.bank_type.eq': clientOrgClassType,

        'import_status.eq': 1,
        // 'bank_type.eq': clientOrgClassType,
      }
    },
    // 有些表没有bank_id只有submit_client_id。。。。。。。。。。。
    normalSubmitParams() {
      const { queryAddressCode, clientOrgClassType } = this.user
      if (!queryAddressCode) {
        this.$message.error('机构配置出错，未添加机构地址')
        throw new Error('该机构没有地址')
      }
      return {
        orWhereAndTemplate: 2,
        'orWhereAnd.submit_client_id.eq': this.clientId,
        'orWhereAnd.bank_type.in': clientOrgClassType,
        'orWhereAnd.address_code.gt': queryAddressCode,
        'orWhereAnd.address_code.lt': getAddressNextValue(queryAddressCode),
        'orWhereAnd.bank_type.eq': clientOrgClassType,

        'import_status.eq': 1,
      }
    },
  },
}

/**
 * 外部必须定义的数据：
 *
 * data
 *   - tableColumns
 *   - tableName
 *   - order
 *   - params
 *
 * methods
 *   - dataAdapter(row)
 *
 */
export default {
  mixins: [limitNormalParams],
  data() {
    return {
      loading: false,
      tableData: [],
      tableCount: 0,
      exportLoading: false,
      useManage: true,
    }
  },
  computed: {
    ...mapGetters(['userId', 'clientId', 'job', 'org', 'user']),
  },
  methods: {
    getParams() {
      return {
        ...this.normalParams,
        ...this.params,
      }
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order || {})
      )
    },
    fetchDataTimeout(params) {
      params.fields = [
        'claim_bank_name',
        'address_name_city',
        'address_name_county',
        'customer_name',
        'org_class_name',
        'parent_main_business',
        'corp_name',
        'corp_phone',
        'is_cert_merge',
        'register_no',
        'lender_idcard',
        'warranty_amount',
        'load_date',
        'load_end_date',
        'warranty_period',
        'create_time',
        'use_category_name',
        'funds_use_dir',
        'gua_contract',
        'iou_no',
        'load_rate',
        'warranty_rate',
        'is_gua_fee_customer',
        'sale_income',
        'assets_total',
        'emp_total',
        'other_cost',
        'income_margin',
        'remark',
        'review_approval',
        'import_status',
        'ex_des',
      ]
      return axios
        .get(
          `/api/credit/${this.tableName}${queryTrouble(this.tableName, params, this.order || {})}`,
          {
            timeout: 0,
          }
        )
        .then(res => res?.data?.data ?? [])
    },
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      const [res = {}] = await this.fetchData(this.getParams())
      this.loading = false

      const data = res.data || {}
      this.tableCount = data.totalCount || 0
      this.tableData = (data.data || []).map(this.dataAdapter)
    },
    async exportExcel(filename, exportData) {
      const exportTable = (
        +(this.params['is_rural_dev.eq'] || '') === 1
          ? exportTableCountyColumns
          : exportTableColumns
      ).filter(item => !item.operations && !item.hidden)
      const header = {}
      if (this.isAbnormal) {
        exportTable.push({ attrs: { label: '异常说明', prop: 'ex_des' } })
      }
      if (this.tableName === 'un_gua_record_view') {
        exportTable.push({ attrs: { label: '解保状态', prop: 'postloanStatus' } })
        exportTable.push({ attrs: { label: '解保金额（万元）', prop: 'un_gua_funds' } })
        exportTable.push({ attrs: { label: '解保日期', prop: 'unGuaDate' } })
      }
      const headerCellStyles = {}
      const columns = exportTable.map((item, i) => {
        const { prop, label } = item.attrs || {}
        header[prop] = label
        headerCellStyles[`${columnToAbc(i)}3`] = { font: { bold: true } }
        // headerCellStyles[`${columnToAbc(i)}2`] = { font: { bold: true } }
        return prop
      })
      let data = []
      if (exportData) {
        data = exportData.map((item, index) => {
          return {
            index: index + 1,
            ...this.dataAdapter(item),
          }
        })
      } else {
        this.exportLoading = true
        const { index, size, subKey, ...params } = this.getParams()
        const [res = {}] = await this.fetchData(params)

        data = (res.data || []).map((item, index) => {
          return {
            index: index + 1,
            ...this.dataAdapter(item),
          }
        })
      }

      const title1 = {
        index: +(this.params['is_rural_dev.eq'] || '') === 1 ? '乡村振兴贷' : '黔农十二贷',
      }
      excelJsonExport({
        columns,
        data: [title1, title1, title1, header, ...data],
        filename,
        styles: {
          border: {
            left: { style: 'thin' },
            top: { style: 'thin' },
            right: { style: 'thin' },
            bottom: { style: 'thin' },
          },
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        merges: ['A1:AE3'],
        cols: [{ wch: 6 }],
        cellStyles: {
          A1: {
            alignment: { horizontal: 'left' },
            font: { bold: true, sz: 24 },
          },
          A2: { alignment: { horizontal: 'left' }, font: { bold: true } },
          ...headerCellStyles,
        },
      }).finally(() => {
        this.exportLoading = false
      })
    },
  },
}
